package com.miaomiao.service.system.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.mail.MailUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.miaomiao.common.RedisPrefix;
import com.miaomiao.common.Result;
import com.miaomiao.domain.system.RegisterBody;
import com.miaomiao.domain.system.User;
import com.miaomiao.domain.system.UserRole;
import com.miaomiao.mapper.system.MenuMapper;
import com.miaomiao.mapper.system.RoleMapper;
import com.miaomiao.mapper.system.UserRoleMapper;
import com.miaomiao.service.system.RegisterService;
import com.miaomiao.service.system.UserService;
import com.miaomiao.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private TemplateEngine templateEngine;


    @Override
    public Result senCode(String email) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200,100,6,20);
        String code = lineCaptcha.getCode();
        String uuid = IdUtil.simpleUUID();
        String key = RedisPrefix.REGISTER_CODE_PRE + uuid;
        DateTime expireTime = DateUtil.offsetMinute(new Date(), 5);

        // 设置渲染到html页面对应的值
        Context context = new Context();
        context.setVariable("SYSTEM_NAME","家具快记管理系统");
        context.setVariable("CODE",code);
        context.setVariable("SYSTEM_URL","http://139.186.109.251/xxjszs");
        context.setVariable("EXPIRE_TIME",expireTime.toString());
        //利用模板引擎加载html文件进行渲染并生成对应的字符串
        String emailContent = templateEngine.process("emailTemplate_registerCode", context);

        MailUtil.send(email,"家具快记管理系统注册邮件",emailContent,true);
        redisCache.setCacheObject(key,code,5, TimeUnit.MINUTES);
        Map<String, String> map = new HashMap<>();
        map.put("uuid",uuid);
        return Result.success(map);
    }

    @Override
    public Result registerUser(RegisterBody registerBody) {
        validateCaptcha(registerBody.getCode(),registerBody.getUuid());
        User user = new User();
        user.setUserName(registerBody.getUsername());
        user.setPassword(registerBody.getPassword());
        user.setRealName(registerBody.getRealName());
        user.setEmail(registerBody.getEmail());
        user.setStuId(registerBody.getStuId());
        user.setCreateBy(registerBody.getUsername());
        user.setUpdateBy(registerBody.getUsername());
        boolean flag;
        try {
             flag = userService.addUser(user);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUserName, registerBody.getUsername());
            user = userService.getOne(queryWrapper);
            Long roleId = roleMapper.getRoleIdByRoleKeyLong("register");
            List<UserRole> userRoleList = new ArrayList<>();
            userRoleList.add(new UserRole(user.getUserId(), roleId));
            flag = flag && userRoleMapper.batchUserRole(userRoleList) > 0;
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("注册失败");
        }
        if(flag){
            return Result.success("注册成功");
        }else{
            return Result.error("注册失败");
        }
    }

    /**
     * 校验验证码
     *
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String code, String uuid) {
        String verifikey = RedisPrefix.REGISTER_CODE_PRE + uuid;
        String verifyCode = redisCache.getCacheObject(verifikey);
        if(verifyCode == null){
            throw new RuntimeException("验证码已失效");
        }
        if(!code.toLowerCase().equals(verifyCode.toLowerCase())){
            throw new RuntimeException("验证码错误");
        }else{
            redisCache.deleteObject(verifikey);
        }
    }
}
